#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Filename: t_plans_ui.py
# Author: ChenChangSong
# Date: 2025-10-17

"""
功能描述: 测试计划页面UI
"""
import openpyxl
from PyQt5.QtWidgets import (
    QGridLayout,
    QHBoxLayout,
    QLabel,
    QLineEdit,
    QPushButton,
    QSpinBox,
    QVBoxLayout,
    QWidget,
    QMessageBox
)
from PyQt5.QtGui import QRegExpValidator
from PyQt5.QtCore import QRegExp
from .common_ui import LogPanel, log_to_ui_info, log_to_ui_error, get_project_root
from function_code.t_plans.t_plans import get_test_plans, create_test_plan, delete_test_plan
class TestPlansPage(QWidget):
    def __init__(self) -> None:
        super().__init__()
        self._init_ui()
    
    def _init_ui(self) -> None:
        root = QVBoxLayout(self)
        root.setSpacing(10)
        root.setContentsMargins(10, 10, 10, 10)
        
        root.addWidget(QLabel("说明！此处功能TAPD套餐过期后无功能入口时，进行增、删、查测试计划的。\n"
        "查询到测试计划链接后，Ctrl+单击打开链接，即可使用测试计划所有的功能！"))
        
        # 使用网格布局确保对齐
        grid_layout = QGridLayout()
        grid_layout.setHorizontalSpacing(10)
        grid_layout.setVerticalSpacing(10)
        grid_layout.setContentsMargins(0, 0, 0, 0)
        
        # 查询功能区域
        grid_layout.addWidget(QLabel("查询创建人:"), 0, 0)
        
        self.query_input = QLineEdit()
        self.query_input.setPlaceholderText("请输入要查询的人名")
        self.query_input.setMaxLength(10)
        grid_layout.addWidget(self.query_input, 0, 1)
        
        # 尝试从配置文件读取默认值
        try:
            # 加载配置文件
            config_path = get_project_root() / "files" / "config_file" / "confg.xlsx"
            wb = openpyxl.load_workbook(str(config_path))
            ws = wb.active
            default_value = ws.cell(row=2, column=5).value or ""
            self.query_input.setText(default_value)
        except Exception as e:
            log_to_ui_error(f"读取配置文件失败: {str(e)}")
        
        # 数字选择器
        self.page_spin = QSpinBox()
        self.page_spin.setRange(1, 99)
        self.page_spin.setValue(1)
        self.page_spin.setPrefix("查询第: ")
        self.page_spin.setSuffix("页")
        grid_layout.addWidget(self.page_spin, 0, 2)
        
        # 查询按钮
        self.query_button = QPushButton("查询测试计划")
        self.query_button.setFixedSize(200, 30)
        grid_layout.addWidget(self.query_button, 0, 3)
        
        # 创建功能区域
        grid_layout.addWidget(QLabel("测试计划名称:"), 1, 0)
        
        self.create_input = QLineEdit()
        self.create_input.setPlaceholderText("请输入需要创建的测试计划名称")
        self.create_input.setMaxLength(99)
        grid_layout.addWidget(self.create_input, 1, 1)
        
        # 创建按钮
        self.create_button = QPushButton("创建测试计划")
        self.create_button.setFixedSize(200, 30)
        grid_layout.addWidget(self.create_button, 1, 3)
        
        # 删除功能区域
        grid_layout.addWidget(QLabel("测试计划ID:"), 2, 0)
        
        self.delete_input = QLineEdit()
        self.delete_input.setPlaceholderText("请输入需要删除的测试计划ID")
        self.delete_input.setMaxLength(20)
        # 只允许输入数字
        self.delete_input.setValidator(QRegExpValidator(QRegExp("[0-9]*")))
        grid_layout.addWidget(self.delete_input, 2, 1)
        
        # 删除按钮
        self.delete_button = QPushButton("删除测试计划")
        self.delete_button.setFixedSize(200, 30)
        grid_layout.addWidget(self.delete_button, 2, 3)
        
        # 设置列宽比例，确保对齐
        grid_layout.setColumnStretch(0, 0)  # 标签列不拉伸
        grid_layout.setColumnMinimumWidth(0, 100)  # 标签列最小宽度
        grid_layout.setColumnStretch(1, 1)  # 输入框列可以拉伸
        grid_layout.setColumnStretch(2, 0)  # 页码列不拉伸
        grid_layout.setColumnMinimumWidth(2, 200)  # 页码列最小宽度
        grid_layout.setColumnStretch(3, 0)  # 按钮列不拉伸
        grid_layout.setColumnMinimumWidth(3, 120)  # 按钮列最小宽度
        
        # 添加网格布局到根布局
        root.addLayout(grid_layout)
        
        # 日志面板
        self.log_panel = LogPanel()
        root.addWidget(self.log_panel)
        
        # 连接信号和槽
        self.query_button.clicked.connect(self._get_test_plans)
        self.create_button.clicked.connect(self._create_test_plan)
        self.delete_button.clicked.connect(self._delete_test_plan)
        
                   
    def _get_test_plans(self):
        # 不再清空屏幕日志，保留历史记录
        
        creator = self.query_input.text().strip()
        page = self.page_spin.value()
        
        try:
            get_test_plans(creator=creator, page=page)
        except Exception as e:
            log_to_ui_error(f"查询失败: {str(e)}")
    
    def _create_test_plan(self):
        # 不再清空屏幕日志，保留历史记录
        
        test_plan_name = self.create_input.text().strip()
        
        if not test_plan_name:
            QMessageBox.warning(self, "警告", "测试计划名称不能为空！")
            return
        
        try:
            create_test_plan(test_plan_name)
            # 不再清空输入框，保留输入内容
        except Exception as e:
            log_to_ui_error(f"创建失败: {str(e)}")
    
    def _delete_test_plan(self):
        # 不再清空屏幕日志，保留历史记录
        
        test_plan_id = self.delete_input.text().strip()
        
        if not test_plan_id:
            QMessageBox.warning(self, "警告", "测试计划ID不能为空！")
            return
        
        # 二次确认
        reply = QMessageBox.question(
            self, "确认删除", 
            f"确定要删除测试计划ID: {test_plan_id}吗？此操作不可逆！",
            QMessageBox.Yes | QMessageBox.No, QMessageBox.No
        )
        
        if reply != QMessageBox.Yes:
            return
        
        try:
            delete_test_plan(test_plan_id)
            # 不再清空输入框，保留输入内容
        except Exception as e:
            log_to_ui_error(f"删除失败: {str(e)}")


